using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DocLibApp
{
    public partial class FormDocument : FormBase
    {
        private string DocumentID = "";
        private string ZipFileName = "";
        private System.Collections.Hashtable htDocument = new System.Collections.Hashtable();

        public FormDocument()
        {
            InitializeComponent();
            SetupGUI();
        }

        /// <summary>
        /// Try to open a document
        /// </summary>
        /// <param name="doc_id"></param>
        /// <returns>false if there is an error that can not open the document</returns>
        public bool OpenDocument(string doc_id)
        {
            bool bFlag = false;
            DocumentID = doc_id;

            System.Collections.Hashtable ht = doc_operation.GetDocumentInformation(doc_id);

            if (ht.Count > 0)
            {
                htDocument = ht;

                string Title = ht["TITLE"].ToString();
                string LastUpdateOn = ht["DT_UPDATE"].ToString();
                string sAuthor = ht["AUTHOR"].ToString();
                string CreatedOn = ht["DT_CREATE"].ToString();

                label_Author.Text = sAuthor;
                label_CreateDate.Text = CreatedOn;
                label_LastUpdate.Text = LastUpdateOn;
                label_Title.Text = Title;

                //Add to most recently used document list
                doc_system.AddToList(def.RecentDocumentList_Group, DocumentID, Title, def.RecentDocumentList_Limit);

                this.Text = "Document [" + doc_id + "]";

                LoadDataFromHashToControls(groupBox_DocumentInfo.Controls, ht);

                ZipFileName = System.IO.Path.Combine(FormMain.DocLib_DocumentPath, doc_id + ".zip");

                RefreshZipFileList();

                bFlag = true;
            }
            else
            {
                ShowMessage("Failed to open document, document not found based on document ID.");
                bFlag = false;
            }

            return bFlag;
        }

        private void RefreshZipFileList()
        {
            //populate file list from zip file
            if (System.IO.File.Exists(ZipFileName))
            {
                if (lsv_FileList.Items.Count > 0)
                    lsv_FileList.Items.Clear();

                System.Collections.Hashtable ht1 = util.GetFileListFromZipFile(ZipFileName, def.ZipPassword);

                foreach (string filename in ht1.Keys)
                {
                    string sSize = ht1[filename].ToString();

                    ListViewItem aitem = new ListViewItem(filename);
                    aitem.SubItems.Add(sSize);
                    aitem.Tag = filename;

                    lsv_FileList.Items.Add(aitem);
                }
            }
        }

        private void SetupGUI()
        {
            util.SetupCombo(cboCategory, FormMain.DocLibStaticValueList, "DOC_CATEGORY");
            util.SetupCombo(cboDocType, FormMain.DocLibStaticValueList, "DOC_TYPE");
            util.SetupCombo(cboOwner, FormMain.DocLibStaticValueList, "DOC_OWNER");
            util.SetupCombo(cboImportance, FormMain.DocLibStaticValueList, "DOC_IMPORTANCE");
            util.SetupCombo(cboDocLocation, FormMain.DocLibStaticValueList, "DOC_LOCATION");
        }

        private void btnViewDocument_Click(object sender, EventArgs e)
        {
            wait_start("Retrieving Document and opening it...");

            util.RunFileWaitForExit(ZipFileName);

            wait_end();
        }

        private void btnSaveFile_Click(object sender, EventArgs e)
        {
            string SaveZipFileName = SelectFile(0, "Save Document Zip File", "ZipFile (*.zip)|*.zip|All files (*.*)|*.*", System.IO.Path.GetFileName(ZipFileName));

            if (!string.IsNullOrEmpty(SaveZipFileName))
            {
                System.IO.File.Copy(ZipFileName, SaveZipFileName);
            }
        }

        private void btnSaveChange_Click(object sender, EventArgs e)
        {
            wait_start("Saving document changes ...");

            System.Collections.Hashtable ht = SaveDataToHashFromControls(groupBox_DocumentInfo.Controls);
            
            ShowMessage(doc_operation.SaveDocumentInformation(DocumentID, ht));

            wait_end();
            this.Close();
        }

        private void CopyDocumentAsNew()
        {
            //certain fields should be new and should not be copy to new document
            string[] RemoveKeyList = { "TITLE", "NOTE", "DOC_ID", "DT_CREATE", "DT_UPDATE", "NUM_PAGES", "ORIGINAL_FILENAME"};

            if (htDocument != null)
            {
                System.Collections.Hashtable ht = htDocument;

                foreach (string key in RemoveKeyList)
                {
                    if (ht.Contains(key))
                        ht.Remove(key);
                }

                FormFileImport fi = new FormFileImport(ht);
                OpenNewMdi(fi);
            }
        }

        private void SaveFileInZipFileList(string filename)
        {
            string sExtension = System.IO.Path.GetExtension(filename);

            string sFileName = SelectFile(0, "Save the selected file from zip to...", "Document file (*." + sExtension + ")|*" + sExtension + "|All Files (*.*)|*.*", filename);

            if (!string.IsNullOrEmpty(sFileName))
            {
                util.ExtractFileFromZip(ZipFileName, filename, System.IO.Path.GetDirectoryName(sFileName), def.ZipPassword);
            }
        }

        private void OpenFileInZipFileList(string filename)
        {
            string sTempPath = System.IO.Path.GetTempPath();
            string sTempFileName = System.IO.Path.Combine(sTempPath, filename);

            try
            {
                util.ExtractFileFromZip(ZipFileName, filename, sTempPath, def.ZipPassword);

                if (System.IO.File.Exists(sTempFileName))
                {
                    util.RunFileWaitForExit(sTempFileName);

                    System.IO.File.Delete(sTempFileName);
                }
            }
            catch (System.Exception ex)
            {
                HandleEx(ex);
            }
        }

        private void AddFilesIntoZipFile(string[] filelist)
        {
            if (ConfirmToProcess("Are you sure you want to add " + filelist.Length.ToString() + " files in the Document Zip File?"))
            {
                List<string> alist = new List<string>();
                alist.AddRange(filelist);

                if (alist.Count > 0)
                {
                    ShowMessage(util.AddFileListIntoExistingZip(alist, ZipFileName, def.ZipPassword, true));
                    
                    RefreshZipFileList();
                }
            }
        }

        private void DeleteFileFromZipFile(string filename)
        {
            try
            {
                util.RemoveFileFromZipFile(ZipFileName, filename, def.ZipPassword);
            }
            catch (System.Exception ex)
            {
                HandleEx(ex);
            }
        }

        private void DeleteDocumentZipFile()
        {
            try
            {
                if (System.IO.File.Exists(ZipFileName))
                    System.IO.File.Delete(ZipFileName);
            }
            catch (System.Exception ex)
            {
                HandleEx(ex);
            }
        }

        private void btnDeleteRecord_Click(object sender, EventArgs e)
        {
            if (ConfirmToProcess("Are you sure you want to delete this document (" + DocumentID + ")?"))
            {
                ShowMessage(doc_operation.DeleteDocument(DocumentID, ConfirmToProcess("Do you want to remove document file too?"), FormMain.DocLib_DocumentPath));
                Close();
            }
        }

        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lsv_FileList.SelectedItems.Count > 0)
            {
                ListViewItem aitem = lsv_FileList.SelectedItems[0];
                string filename = aitem.Tag.ToString();

                OpenFileInZipFileList(filename);
            }
        }

        private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lsv_FileList.SelectedItems.Count > 0)
            {
                foreach (ListViewItem aitem in lsv_FileList.SelectedItems)
                {
                    if (aitem.Tag != null)
                    {
                        string filename = aitem.Tag.ToString();

                        SaveFileInZipFileList(filename);
                    }
                }
            }
        }

        private void lsv_FileList_DoubleClick(object sender, EventArgs e)
        {
            if (lsv_FileList.SelectedItems.Count > 0)
            {
                ListViewItem aitem = lsv_FileList.SelectedItems[0];
                string filename = aitem.Tag.ToString();

                OpenFileInZipFileList(filename);
            }
        }

        private void removeFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lsv_FileList.SelectedItems.Count > 0)
            {
                foreach (ListViewItem aitem in lsv_FileList.SelectedItems)
                {
                    if (aitem.Tag != null)
                    {
                        string filename = aitem.Tag.ToString();
                        if (ConfirmToProcess("Are you sure you want to remove file [" + filename + "] from the zip?"))
                        {
                            DeleteFileFromZipFile(filename);

                            lsv_FileList.Items.Remove(aitem);

                            //ask if want to remove the zip file if there are no longer anything in it
                            if (lsv_FileList.Items.Count == 0 && ConfirmToProcess("Do you want to remove the zip file?"))
                            {
                                DeleteDocumentZipFile();
                            }
                        }
                    }
                }
            }
        }

        private void FormDocument_DragEnter(object sender, DragEventArgs e)
        {
            // If the data is a file or a bitmap, display the copy cursor.
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void FormDocument_DragDrop(object sender, DragEventArgs e)
        {
            string[] asFiles = e.Data.GetData(DataFormats.FileDrop) as string[];

            if (asFiles != null)
            {
                AddFilesIntoZipFile(asFiles);
            }
        }

        private void addFilesToZipToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 3;
            openFileDialog1.Multiselect = true;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog1.FileNames.Length > 0)
                {
                    AddFilesIntoZipFile(openFileDialog1.FileNames);
                }
            }
        }

        private void btnCopyAsNew_Click(object sender, EventArgs e)
        {
            CopyDocumentAsNew();
        }

        private void btnAudit_Click(object sender, EventArgs e)
        {
            FormAudit aForm = new FormAudit(DocumentID);
            OpenNewMdi(aForm);
        }
    }
}